import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Divider,
  Tag,
  Table,
  Pagination,
  Spin,
  Upload,
  AutoComplete,
  Radio,
  Popconfirm,
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './CustomerManagement.less';
import AddCustomer from '../../components/Falcon/Customer/AddCustomer';

import { validatemobile } from '../../utils/utils';
import TextArea from 'antd/lib/input/TextArea';
import { timingSafeEqual } from 'crypto';

const { Description } = DescriptionList;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const Option = Select.Option;
const { MonthPicker, RangePicker } = DatePicker;
const RadioGroup = Radio.Group;
const InputGroup = Input.Group;

/*
  客户管理
*/

@connect(({ customer }) => ({
  customer,
}))
@Form.create()
export default class CustomerManagement extends PureComponent {
  state = {
    dataTimeFlag: false,
    modalVisible: false,
    idcardFlag: false,
    fieldsValue: {},
    dataTime: [],
    idcardNum: '',
    cardType: 1,
    idtype: 1,
    birthday: '',
    age: '',
    sex: '',
    searchFilters: {
      custName: '',
      idcard: '',
      phone: '',
      startDate: '',
      endDate: '',
    },
  };

  handleAddCustomerOnOK = () => {
    const { dispatch } = this.props;
    const form = this.formRef.props.form;
    // console.log("handleAddCustomerOnOK", form)
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      // console.log('Received values of form: ', values);
      form.resetFields();
      this.props.dispatch({
        type: 'customer/createCustomer',
        payload: {
          ...values,
        },
        callback: () => {
          const { customer: { customerResult, customerLoading } } = this.props;
          if (customerResult.code == '200') {
            message.success('添加成功');
            this.setState({
              modalVisible: false,
            });
            dispatch({
              type: 'customer/fetchCustomer',
              payload: {
                offset: 0,
                limit: 10,
              },
            });
          } else {
            message.error(customerResult.message);
          }
        },
      });
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'customer/fetchCustomer',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  }

  handleSearch = e => {
    // e.preventDefault();
    this.props.dispatch({
      type: 'customer/fetchCustomer',
      payload: {
        offset: 0,
        limit: 10,
        custName: this.state.searchFilters.custName,
        idcard: this.state.searchFilters.idcard,
        phone: this.state.searchFilters.phone,
        createTimeBegin: this.state.searchFilters.startDate,
        createTimeEnd: this.state.searchFilters.endDate,
      },
    });
  };

  handleSearchCustNameChange = e => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        custName: e.target.value,
      },
    });
  };

  handleSearchIdcardChange = e => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        idcard: e.target.value,
      },
    });
  };

  handleSearchPhoneChange = e => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        phone: e.target.value,
      },
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      dataTime: [],
      value: '',
      dataTimeFlag: false,
      searchFilters: {
        ...this.state.searchFilters,
        custName: '',
        idcard: '',
        phone: '',
        startDate: '',
        endDate: '',
      },
    });
    dispatch({
      type: 'customer/fetchCustomer',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  };

  handleChangeTime = (dates, dateString) => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        startDate: dates[0],
        endDate: dates[1],
      },
    });
  };

  hanleTreeSelectChange = (value, info) => {
    this.setState({
      value: value,
      searchFilters: {
        ...this.state.searchFilters,
        branchName: info,
      },
    });
  };

  deleteCustomer = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customer/deleteCustomer',
      payload: {
        id: id,
      },
      callback: () => {
        dispatch({
          type: 'customer/fetchCustomer',
          payload: {
            offset: 0,
            limit: 10,
          },
        });
      },
    });
  };

  handleAddCustomer = () => {
    this.setState({
      modalVisible: true,
      addCustomerShow: true,
    });
  };

  handleOnCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="客户姓名">
              {/* {getFieldDecorator('dealerName')(<Input placeholder="请输入" />)} */}
              <Input
                placeholder="请输入"
                value={this.state.searchFilters.custName}
                onChange={this.handleSearchCustNameChange}
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="身份证号">
              <Input
                placeholder="请输入"
                value={this.state.searchFilters.idcard}
                onChange={this.handleSearchIdcardChange}
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="联系电话">
              <Input
                placeholder="请输入"
                value={this.state.searchFilters.phone}
                onChange={this.handleSearchPhoneChange}
              />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="创建时间">
              <div>
                <RangePicker
                  style={{ width: '100%' }}
                  allowClear={true}
                  showToday={true}
                  onChange={this.handleChangeTime}
                  value={[
                    this.state.dataTimeFlag ? null : this.state.searchFilters.startDate,
                    this.state.dataTimeFlag ? null : this.state.searchFilters.endDate,
                  ]}
                  showTime={{ hideDisabledOptions: true }}
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={24} sm={24}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={this.handleAddCustomer}>
                添加客户
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  columns = [
    {
      title: '客户编号',
      dataIndex: 'custNo',
      key: 'custNo',
    },
    {
      title: '客户姓名',
      dataIndex: 'custName',
      key: 'custName',
    },
    {
      title: '身份证号',
      dataIndex: 'idcard',
      key: 'idcard',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      render: (text, record) => (
        //0:未激活；1：正常；2：已启动；3：已暂停
        <Fragment>
          <Link to={`/customer/customer-details?id=${record.id}&state=1`}>详情</Link>
          <Divider type="vertical" />
          {/* <a  onClick={()=>this.deleteCustomer(record.id)}>删除 </a> */}
          <Popconfirm title="是否要删除此客户？" onConfirm={() => this.deleteCustomer(record.id)}>
            <a>删除</a>
          </Popconfirm>
          <Divider type="vertical" />
          <Link to={`/customer/customer-sales-tracking?id=${record.id}&state=1`}>销售跟踪</Link>
        </Fragment>
      ),
    },
  ];

  handleStandardTableChange = e => {
    const { dispatch } = this.props;
    // e.preventDefault();
    dispatch({
      type: 'customer/fetchCustomer',
      payload: {
        offset: (e.current - 1) * e.pageSize,
        limit: e.pageSize,
        custName: this.state.searchFilters.custName,
        idcard: this.state.searchFilters.idcard,
        phone: this.state.searchFilters.phone,
        createTimeBegin: this.state.searchFilters.startDate,
        createTimeEnd: this.state.searchFilters.endDate,
      },
    });
    // this.props.dispatch({
    //     type: 'customer/fetchCustomer',
    //     payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
    // });
  };

  handleChangeIdCard = e => {
    const { dispatch } = this.props;
    this.setState({
      idcardNum: e.target.value,
    });
    if (this.state.cardType == 1) {
      if (e.target.value.length == 15 || e.target.value.length == 18) {
        dispatch({
          type: 'customer/existIdcard',
          payload: {
            idcard: e.target.value,
          },
          callback: () => {
            const { customer: { customerResult, customerLoading } } = this.props;
            if (customerResult.code != '200') {
              message.error(customerResult.message);
              this.setState({
                idcardFlag: true,
              });
            } else {
              this.setState({
                idcardFlag: false,
              });
            }
          },
        });
      }
    }
  };

  handleCardTypeSelect = value => {
    this.setState({
      cardType: value,
    });
  };

  handleJudgeIdCardNum = num => {
    if (this.state.idcardNum != '') {
      if (num == 1) {
        const idcardList = this.state.idcardNum.split('');
        if (idcardList[16] % 2 == 0) {
          this.setState({
            sex: '女',
          });
          return '女';
        } else {
          this.setState({
            sex: '男',
          });
          return '男';
        }
      }
      if (num == 2) {
        const idcardList = this.state.idcardNum; //.split('')
        const myDate = new Date();
        const month = myDate.getMonth() + 1;
        const day = myDate.getDate();
        let age = myDate.getFullYear() - idcardList.substring(6, 10) - 1;
        if (
          idcardList.substring(10, 12) < month ||
          (idcardList.substring(10, 12) == month && idcardList.substring(12, 14) <= day)
        ) {
          age++;
        }
        this.setState({
          age: age,
        });
        return age;
      }
      if (num == 3) {
        const idcardList = this.state.idcardNum;
        let birthday =
          idcardList.substring(6, 10) +
          '-' +
          idcardList.substring(10, 12) +
          '-' +
          idcardList.substring(12, 14);
        this.setState({
          birthday: birthday,
        });
        return birthday;
      }
    }
  };

  saveFormRef = formRef => {
    // console.log("saveFormRef", formRef)
    this.formRef = formRef;
  };

  render() {
    const { customer: { customerList, customerPage, customerLoading } } = this.props;
    const { getFieldDecorator, form, dispatch } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderLayout title="客户维护">
        {/* {JSON.stringify(customerList)} */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderAdvancedForm()}</div>
            <Table
              dataSource={customerList}
              pagination={customerPage}
              columns={this.columns}
              loading={customerLoading}
              rowKey="id"
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title="客户新增"
          visible={this.state.modalVisible}
          onCancel={this.handleOnCancel}
          onOk={this.handleAddCustomerOnOK}
        >
          <AddCustomer marriageShow={false} wrappedComponentRef={this.saveFormRef} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
